package com.example.taobao;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class lineMainActivity2 extends AppCompatActivity {

    private EditText mSocketIDEdt, mMessageEdt;
    private StringBuffer mConsoleStr = new StringBuffer();//储存和操作字符串
    private Socket mSocket;
    private boolean isStartRecieveMsg;
    private RecyclerView rv;
    private SocketHandler mHandler;//网络日志记录
    protected BufferedReader mReader;
    protected BufferedWriter mWriter;
    private static final int COMPLETED = 1;
    private ArrayList<MyBean> list;
    private MyAdapter adapter;
    Thread thread;
    private static boolean flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_line_main2);
        initView();
    }

    private void initView() {

        mSocketIDEdt = (EditText) findViewById(R.id.socket_id_edt);
        mMessageEdt = (EditText) findViewById(R.id.msg_edt);
        findViewById(R.id.start_btn).setOnClickListener(onClickListener);
        findViewById(R.id.send_btn).setOnClickListener(onClickListener);
        findViewById(R.id.stop_btn).setOnClickListener(onClickListener);
        mHandler = new SocketHandler();
        rv = (RecyclerView) findViewById(R.id.rv);
        list = new ArrayList<>();
        adapter = new MyAdapter(this);
        rv.setAdapter(adapter);
        LinearLayoutManager manager = new LinearLayoutManager(lineMainActivity2.this, LinearLayoutManager.VERTICAL, false);
        rv.setLayoutManager(manager);//设置布局
    }

    private void initSocket() {
        thread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    isStartRecieveMsg = true;
                    mSocket = new Socket("192.168.0.101", 2000);
                    mReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream(), "utf-8"));
                    mWriter = new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "utf-8"));
                    while (isStartRecieveMsg) {
                        if (mReader.ready()) {
                            mHandler.obtainMessage(0, mReader.readLine()).sendToTarget();

                        }
                        Thread.sleep(200);
                    }
                    mWriter.close();
                    mReader.close();
                    mSocket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();

    }


    public View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.send_btn:
                    send();
                    break;
                case R.id.start_btn:
                    if (!isStartRecieveMsg) {
                        initSocket();
                    }
                    break;
                case R.id.stop_btn:
                    flag = true;
                    System.err.println("中断");
                default:
                    break;
            }

        }
    };

    private void send() {

        new AsyncTask<String, Integer, String>() {//这个异步任务不需要线程方便，

            @Override
            protected String doInBackground(String... params) {
                sendMsg();
                return null;
            }
        }.execute();
    }

    protected void sendMsg() {
        try {
            String socketID = mSocketIDEdt.getText().toString().trim();
            String msg = mMessageEdt.getText().toString().trim();
            JSONObject json = new JSONObject();
            json.put("to", socketID);
            json.put("msg", msg);
            mWriter.write(json.toString() + "\n");
            mWriter.flush();
            mConsoleStr.append("我" + msg + "   " + getTime(System.currentTimeMillis()) + "\n");
            MyBean bean = new MyBean("我", 2, msg, getTime(System.currentTimeMillis()));
            list.add(bean);
            /**
             * 在子线程更新UI
             */
            Message message = new Message();
            message.what = COMPLETED;
            mHandler.sendMessage(message);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    class SocketHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    try {
                        JSONObject json = new JSONObject((String) msg.obj);
                        MyBean bean = new MyBean(json.getString("from"), 1, json.getString("msg"), getTime(System.currentTimeMillis()));
                        list.add(bean);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // 向适配器set数据
                    adapter.setData(list);
                    rv.setAdapter(adapter);
                    LinearLayoutManager manager = new LinearLayoutManager(lineMainActivity2.this, LinearLayoutManager.VERTICAL, false);
                    rv.setLayoutManager(manager);
                    rv.scrollToPosition(adapter.getItemCount() - 1);//recycleview滑到底部

                    break;
                case 1:

                    // 向适配器set数据
                    adapter.setData(list);
                    rv.setAdapter(adapter);
                    manager = new LinearLayoutManager(lineMainActivity2.this, LinearLayoutManager.VERTICAL, false);
                    rv.setLayoutManager(manager);
                    rv.scrollToPosition(adapter.getItemCount() - 1);//recycleview滑到底部

                    break;
                default:
                    break;
            }
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    private String getTime(long millTime) {
        Date d = new Date(millTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.format(d));
        return sdf.format(d);
    }
}